/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.org.pslava.codingtest.delegates;

import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;

/**
 * Encapsulates a functionality of Calculate Delegate. <br/>
 *
 * 
 * @author Vyacheslav Panasyuk.
 */
public class CountCalculateDelegator implements ICalculateDelegate {

    public Double calculate(Integer count, HashMap<Integer, Double> prices) {
        Double result = 0.0;

        Integer[] cnt = (Integer[]) prices.keySet().toArray(new Integer[prices.keySet().size()]);
        Arrays.sort(cnt, new Comparator<Integer>() {
            //<editor-fold defaultstate="collapsed" desc="sorting array">

            public int compare(Integer t, Integer t1) {
                if (t.equals(t1)) {
                    return 0;
                }
                if (t < t1) {
                    return 1;
                } else {
                    return -1;
                }
            }
        });
        //</editor-fold>
        for (Integer cntProduct : cnt) {
            double price = prices.get(cntProduct);
            while (count >= cntProduct) {
                result += price;
                count -= cntProduct;
            }
        }
        return result;

    }
}
